#include "Reactor.hpp"
#include "Sock.hpp"
#include "Acceptor.hpp"
#include "Util.hpp"

void Usage(std::string proc)
{
  std::cout << "Usage: " << proc << " port" << std::endl;
}

/*
 *  实现ET模式
 * 
*/
int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, static_cast<uint16_t>(atoi(argv[1])));
    Sock::Listen(listen_sock);

    // Reactor初始化
    Reactor *R = new Reactor;
    if(nullptr == R)
    {
        throw std::bad_alloc();
    }

    R->InitReactor();
    // Event初始化
    Event* event = new Event;
    if(nullptr == event)
    {
        throw std::bad_alloc();
    }
    event->_sock = listen_sock;
    // Event指向反应堆
    event->_R = R;
    // 设置为非阻塞
    SetNonBlock(listen_sock);
    // 注册回调方法
    event->RegisterCallback(Acceptor, nullptr, nullptr);
    // 向反应堆添加柴火
    R->InsertEvent(event, EPOLLIN | EPOLLET);
    //R->InsertEvent(event, EPOLLIN); // LT模式
    // 循环派发事件
    for( ; ;)
      R->Dispatcher(1000);
     
    return 0;
}
